<?php

// Namespace

namespace Loop;


/**
 * CQuota
 *
 * @package		Loop
 * @category	Model
 */

abstract class CQuota extends \Loop\CObject
{	
	/**
	 *
	 */
	
	protected function createProperties()
	{
		$this->createProperty
		(
			'name',
			array 
			(
				'type' => TYPE_STRING_MEDIUM
			)
		);

		$this->createProperty
		(
			'nbRequests',
			array 
			(
				'type' => TYPE_INTEGER
			)
		);	

		$this->createProperty
		(
			'nbTimes',
			array 
			(
				'type' => TYPE_INTEGER
			)
		);

		$this->createProperty
		(
			'nbTimesMetrics',
			array 
			(
				'type' => TYPE_TIME_METRIC
			)
		);
	}


	/**
	 *
	 */

	public function isQuotaExceeded()
	{
		require_once(PATH_LOOP . 'Model/CQuotaInstance.php');

		$quotaInstance = new CQuotaInstance();


		$nbRequests = $this->getNbRequests();
		$nbTimes = $this->getNbTimes();
		$nbTimesMetric = $this->getNbTimesMetrics();


		$currentTime = time();
		$defaultTimeOfStart = app()->getTimeHelper()->getStartTimeFromMetric($nbTimesMetric);


		$rawQuotaInstance = $quotaInstance->find
		(
			array
			(
				'conditions' => array
				(
					'timeOfCreation' => array(BETWEEN, array($defaultTimeOfStart, $currentTime)),
					'status' => array(EQUAL, 'not_reached'),
					'quotaId' => array(EQUAL, $this->getId())
				)
			)			
		);


		if (count($rawQuotaInstance) >= $nbRequests)
		{
			$quotaInstance->setStatus('exceeded');
			$quotaInstance->setTrace
			(
				json_encode
				(
					array
					(
						'nbRequests' => $nbRequests,
						'nbFoundRequests' => count($rawQuotaInstance),
						'status' => 'exceeded'
					)
				)
			);

			$isQuotaExceeded = true;
		}
		else
		{
			$quotaInstance->setStatus('not_reached');
			$quotaInstance->setTrace
			(
				json_encode
				(
					array
					(
						'nbRequests' => $nbRequests,
						'nbFoundRequests' => count($rawQuotaInstance),
						'status' => 'not_reached'
					)
				)
			);

			$isQuotaExceeded = false;
		}

		$quotaInstance->setQuotaId($this->getId());

		$quotaInstance->save();


		return $isQuotaExceeded;
	}
}

?>
